import React, {useEffect, useState} from "react";
import http from "../request";
import {Select} from "antd";

const {Option} = Select;

const Store = (props) => {
    const [list, setList] = useState([[], []])

    useEffect(() => {
        init()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    return (
        <div className={`${props.className}`}>
            <Select value={props.value[0]} onChange={e => storeChange(e)} allowClear placeholder="部门" style={{width: 120}}>
                { list[0].map(e => <Option value={e.id} key={e.id}>{e.name}</Option>) }
            </Select>
            <Select value={props.value[1]} onChange={e => staffChange(e)} allowClear placeholder="员工" className="u-m-l-10" style={{width: 120}}>
                { list[1].map(e => <Option value={e.id} key={e.id}>{e.nickname}</Option>) }
            </Select>
        </div>
    )

    async function init(){
        try {
            let newList = {...list}
            const {data:store} = await http('store.list')
            newList[0] = store.rows
            if(props.value[0] > 0){
                const {data:staff} = await http('user.list', {
                    store_id: props.value[0]
                })
                newList[1] = staff
            }
        setList(newList)
        } catch (error) {
            console.log(error);
        }
    }
    function storeChange(store_id){
        props.onChange(store_id)
        let newList = {...list}
        if(store_id > 0){
            http('user.list', {store_id}).then(res => {
                if(res.code === 1){
                    newList[1] = res.data
                    setList(newList)
                }
            })
        } else {
            newList[1] = []
            setList(newList)
        }
    }
    function staffChange(staff_id){
        props.onChange(props.value[0], staff_id)
    }
}

export default Store;